import type { Announcement } from "@/interface/announcementData";
import { computed, ref } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import type { Form } from "@/interface/formData";
import { useUserStore } from "@/stores/userStore";
import type { JobInfo } from "@/interface/jobInfoData";


export default function () {

    const { useridentityfer } = useUserStore();

    const works = ref<Form[]>([]); //请求后数据集
    const workInfos = ref();
    const completeWork = ref<Form[]>([]);



    //后端请求数据
    //待审核职位
    async function getWorks() {
        await axios.get("/api/institute/works")
            .then(response => {
                works.value = response.data.data;
            })
            .catch(error => {
                ElMessage.warning("请求失败");
            })
    }

    async function getCompleteWorks() {
        await axios.get(`/api/institute/completeworks/${useridentityfer}`)
            .then(response => {
                completeWork.value = response.data.data;
            })
            .catch(error => {
                ElMessage.warning("请求失败");
            })
    }

    async function getWorkInfos() {
        await axios.get(`/api/institute/workInfos/${useridentityfer}`)
            .then(response => {
                workInfos.value = response.data.data;
            })
            .catch(error => {
                ElMessage.warning("请求失败");
            })
    }

    async function getAnnouncements() {
        const date = new Date();
        const month = date.getMonth() + 1;
        await axios.get(`/api/institute/announcements/${month}`)
            .then(response => {
                announcements.value = response.data.data;
            })
            .catch(error => {
                ElMessage.warning("请求失败");
            })
    }

    // 状态卡片

    let underReview = ref();
    let failReviewNumber = ref()
    let receivedNumbe = ref()

    function statusCardInit() {
        let receivedjob = workInfos.value.filter((work: JobInfo) => {
            return work.examineOption == "同意" || work.examineOption == "批量同意"
        })
        let failReviewJob = workInfos.value.filter((work: JobInfo) => {
            return work.examineOption == "驳回" || work.examineOption == "批量驳回"
        })

        underReview.value = works.value.length;   //待审核
        receivedNumbe.value = receivedjob.length;
        failReviewNumber.value = failReviewJob.length;
    }

    const statusCard = computed(() => {
        return {
            underReview: underReview.value, //待审核
            failReviewNumber: failReviewNumber, //驳回职位
            receivedNumbe: receivedNumbe, //已处理
        };
    });



    // 公告
    const announcements = ref<Announcement[]>([]);

    // 图表

    //存储订单中每个状态的type数量
    const workStatusCount = ref<Record<string, Record<string, number>>>({});
    const completeWorkStatusCount = ref<Record<string, Record<string, number>>>({});


    function countWorks(data: Form[]) {
        // 初始化统计对象
        const statusMap: Record<string, Record<string, number>> = {};

        data.forEach((work) => {
            const { status, jobType } = work;

            // 统计 status
            if (!statusMap[status]) {
                statusMap[status] = { "1": 0, "2": 0, "3": 0 };
            }
            statusMap[status][jobType] = (statusMap[status][jobType] || 0) + 1;
        });

        workStatusCount.value = statusMap;
    }

    function countCompleteWorks(data: Form[]) {
        // 初始化统计对象
        const statusMap: Record<string, Record<string, number>> = {};

        data.forEach((work) => {
            const { process, status, jobType } = work;

            // 统计 status
            if (!statusMap[status]) {
                statusMap[status] = { "1": 0, "2": 0, "3": 0 };
            }
            statusMap[status][jobType] = (statusMap[status][jobType] || 0) + 1;
        });

        completeWorkStatusCount.value = statusMap;

    }

    // 更新 source 数据，确保所有数据已准备好后再赋值
    function updateSource() {
        source.value = [
            {
                product: "所有申请",
                零工:
                    completeWorkStatusCount.value["2"]?.["1"] + completeWorkStatusCount.value["3"]?.["1"] + workStatusCount.value["1"]?.["1"],
                短期兼职:
                    completeWorkStatusCount.value["2"]?.["2"]
                    + completeWorkStatusCount.value["3"]?.["2"]
                    + workStatusCount.value["1"]?.["2"],
                长期兼职:
                    completeWorkStatusCount.value["2"]?.["3"]
                    + completeWorkStatusCount.value["3"]?.["3"]
                    + workStatusCount.value["1"]?.["3"],
            },
            {
                product: "待审核职位",
                零工: workStatusCount.value["1"]?.["1"],
                短期兼职: workStatusCount.value["1"]?.["2"],
                长期兼职: workStatusCount.value["1"]?.["3"],
            },
            {
                product: "已审核",
                零工: completeWorkStatusCount.value["2"]?.["1"] + completeWorkStatusCount.value["3"]?.["1"],
                短期兼职: completeWorkStatusCount.value["2"]?.["2"] + completeWorkStatusCount.value["3"]?.["2"],
                长期兼职: completeWorkStatusCount.value["2"]?.["3"] + completeWorkStatusCount.value["3"]?.["3"],
            }
        ];
    }

    const source = ref<
        { product: string; 零工: number; 短期兼职: number; 长期兼职: number }[]
    >([]);

    const ChartData = ref({
        dimensions: ["product", "零工", "短期兼职", "长期兼职"],
        source: source,
    });

    //数据初始化

    async function DateInit() {
        await getWorkInfos();
        await getWorks();
        await getAnnouncements();
        await getCompleteWorks();
        statusCardInit();
        countWorks(works.value);
        countCompleteWorks(completeWork.value);
        updateSource();
    }

    return { statusCard, announcements, ChartData, DateInit, source };
}
